package com.jinglvhuanjing.app.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.LinearLayoutCompat;

import com.jinglvhuanjing.app.R;
import com.jinglvhuanjing.app.bean.LogEvent;
import com.jinglvhuanjing.app.bean.RunEvent;
import com.jinglvhuanjing.app.bean.param.ParamLayout5Bean;
import com.jinglvhuanjing.app.listener.SwitchEvent;
import com.jinglvhuanjing.app.utils.ByteUtil;
import com.jinglvhuanjing.app.utils.LOG;
import com.jinglvhuanjing.app.utils.SerialMsgHandler;
import com.jinglvhuanjing.app.utils.SingletonSerl;
import com.jinglvhuanjing.app.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class SignalOutPanelView extends LinearLayoutCompat {
    private String TAG = "输出控制";

    public SignalOutPanelView(@NonNull Context context) {
        super(context);
        this.init(context);
    }

    public SignalOutPanelView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.init(context);
    }

    public SignalOutPanelView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.init(context);
    }

    /*** 1号投口 ***/
    private SignalOutPanelItemView signal_out_tk_1;
    /*** 2号投口 ***/
    private SignalOutPanelItemView signal_out_tk_2;
    /*** 3号投口 ***/
    private SignalOutPanelItemView signal_out_tk_3;
    /*** 4号投口 ***/
    private SignalOutPanelItemView signal_out_tk_4;
    /*** 5号投口 ***/
    private SignalOutPanelItemView signal_out_tk_5;

    private ArrayList<SignalOutPanelItemView> itemViews = new ArrayList<>();

    /*** 解析收到的投口信息 ***/
    Handler mHandlerKz = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    String obj = (String) msg.obj;
                    if (!StringUtils.isEmpty(obj)) {
                        byte[] bytes_ = ByteUtil.hexStringToBytes(obj);
                        if (bytes_ != null && bytes_.length > 1) {
                            // 03 功能码，轮询信息返回
                            if (bytes_[1] == SingletonSerl.byte_gnm_cssz && bytes_.length > 7) {
                                LOG.e(TAG, "读取内容:" + obj);
                                parseByte(bytes_);
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Subscribe
    public void onEvent(RunEvent event) {
        String hex = ByteUtil.hexBytesToString(event.getValue());
        LOG.e(SerialMsgHandler.TAG, TAG+"-读取内容:" + hex);
        Message message = this.mHandlerKz.obtainMessage();
        message.what = 0;
        message.obj = hex;
        this.mHandlerKz.sendMessage(message);
    }

    /**
     * @param bytes
     */
    public void parseByte(byte[] bytes) {
        LogEvent logEvent = new LogEvent();
        logEvent.setTAG(TAG);
        String jcqdz = ByteUtil.hexBytesToString(new byte[]{bytes[2], bytes[3]});
        LOG.e(TAG, "寄存器地址："+jcqdz);
        String lx = SingletonSerl.getJCQDZLX_SCKZ(jcqdz);
        LOG.e(TAG, "类型："+lx);
        if (!"未知".equals(lx)) {
            String bw = ByteUtil.hexBytesToString(bytes);
            logEvent.setValue(
                    String.format("【%s号投口】<%s>设置%s:%s"
                            , ByteUtil.hexByteToString(bytes[0])
                            , lx
                            , "成功"
                            , StringUtils.subStringToSpace(bw, 2))
            );
            EventBus.getDefault().post(logEvent);
        }
    }

    private void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.view_signal_out_panel_layout, this, true);
        this.signal_out_tk_1 = findViewById(R.id.signal_out_tk_1);
        this.signal_out_tk_2 = findViewById(R.id.signal_out_tk_2);
        this.signal_out_tk_3 = findViewById(R.id.signal_out_tk_3);
        this.signal_out_tk_4 = findViewById(R.id.signal_out_tk_4);
        this.signal_out_tk_5 = findViewById(R.id.signal_out_tk_5);

        itemViews.add(this.signal_out_tk_1);
        itemViews.add(this.signal_out_tk_2);
        itemViews.add(this.signal_out_tk_3);
        itemViews.add(this.signal_out_tk_4);
        itemViews.add(this.signal_out_tk_5);
        int index = 1;
        for (SignalOutPanelItemView itemView : itemViews) {
            itemView.setLabel(String.format("%s号投口", index));
            index++;
        }

        this.signal_out_tk_1.setParamTag("输出控制_1号投口", ParamLayout5Bean.PARAM_KEY_XHSCKZ_TK_1);
        this.signal_out_tk_2.setParamTag("输出控制_2号投口", ParamLayout5Bean.PARAM_KEY_XHSCKZ_TK_2);
        this.signal_out_tk_3.setParamTag("输出控制_3号投口", ParamLayout5Bean.PARAM_KEY_XHSCKZ_TK_3);
        this.signal_out_tk_4.setParamTag("输出控制_4号投口", ParamLayout5Bean.PARAM_KEY_XHSCKZ_TK_4);
        this.signal_out_tk_5.setParamTag("输出控制_5号投口", ParamLayout5Bean.PARAM_KEY_XHSCKZ_TK_5);

        addSwitchEvent(new SwitchEvent() {
            @Override
            public void switchCallBack(String label, String key, boolean isOpen) {
                Log.w(TAG, String.format("label=%s,key=%s,isOpen=%s", label, key, isOpen));
            }

            @Override
            public void switchCallBack_(String label, String tkdz, String hex) {
                Log.w(TAG, String.format("label=%s,tkdz=%s,hex=%s", label, tkdz, hex));
                try {
                    SingletonSerl singletonSerl = SingletonSerl.getInstance();
                    String bw = singletonSerl.write(TAG, singletonSerl.signalOutPanel(tkdz, hex));
                    eventBus(tkdz, TAG, bw);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        SerialMsgHandler.getInstance().setStartListener(true, this.mHandlerKz);
        EventBus.getDefault().register(this);
    }

    public void onDestroy() {
        try {
            EventBus.getDefault().unregister(this);
        }catch (Exception e){

        }
    }

    public void addSwitchEvent(SwitchEvent switchEvent) {
        for (SignalOutPanelItemView itemView : itemViews) {
            itemView.addSwitchEvent(switchEvent);
        }
    }

    /**
     * 获取值
     *
     * @return 集合
     */
    public ArrayList<HashMap<String, String>> getFormValue() {
        ArrayList<HashMap<String, String>> values = new ArrayList<>();
        for (SignalOutPanelItemView itemView : itemViews) {
            values.add(itemView.getFormValue());
        }
        return values;
    }

    private void eventBus(String tkdz, String type, String bw) {
        LogEvent logEvent = new LogEvent();
        logEvent.setTAG(TAG);
        logEvent.setValue(
                String.format("【%s号投口】<%s>发送:%s"
                        , ByteUtil.hexStringToInt(tkdz)
                        , type
                        , StringUtils.subStringToSpace(bw, 2)));
        EventBus.getDefault().post(logEvent);
    }

}
